<?php
class Admin_Model_Category extends Zend_Db_Table_Abstract
{
    protected $_mainTable = 'categories';

    protected $_idFieldName = 'p_categories';

	public function getCollection($numVente)
	{
		$sql = $this->getAdapter()->select()
		->from($this->_mainTable)
		->where('deleted = 0 AND f_ventes = ?', $numVente)
		->order('ordre', 'nom');
        return $sql;
		//return $this->getAdapter()->fetchAll($sql);
	}

	public function getCollectionPrec($numVente)
	{
	    $sql = 'select distinct(nom),tva
        	from categories
        	where f_ventes in (select p_ventes from ventes where type_vente = (select type_vente from ventes where p_ventes = ' . $numVente . ') and ventes.deleted = 0)
        	and p_categories not in (select p_categories from categories where f_ventes = ' . $numVente . ')
        	and categories.deleted=0
        	group by nom,tva
        	order by nom';
	    return $this->getAdapter()->fetchAll($sql);
	}

	public function getCategory($id)
	{
		$sql = $this->getAdapter()->select()
		->from($this->_mainTable)
		->where('p_categories = ?', $id);
		return $this->getAdapter()->fetchRow($sql);
	}

	public function save($data, $id = null)
	{
	    if (!$id) {
	        $this->getAdapter()->insert($this->_mainTable, $data);
	    } else {
	        $where = $this->getAdapter()->quoteInto($this->_idFieldName . ' = ?', $id);
	        $this->getAdapter()->update($this->_mainTable, $data, $where);
	    }

	    return true;
	}

	public function recover($recovers, $numVente)
	{
	    foreach ($recovers as $choix) {
	        $select = $this->getAdapter()->select()->from($this->_mainTable, array('number' => 'COUNT(*)'))
	        ->where('nom = ?', $choix)
	        ->where('f_ventes = ?', $numVente);
	        if ($this->getAdapter()->fetchOne($select) == 0) {
	            $select = $this->getAdapter()->select()->from($this->_mainTable, array('tva'))
	            ->where('nom = ?', $choix)
	            ->limit(1);
	            $tva = $this->getAdapter()->fetchOne($select);
	            print_r($tva);
	            $data = array(
                    'nom' => $choix,
                    'tva' => $tva,
                    'f_ventes' => $numVente
                );
	            $this->getAdapter()->insert($this->_mainTable, $data);
	        }
	    }
	    return true;
	}
}